const { query, beginTransaction, commitTransaction, rollbackTransaction } = require('../config/db');
const { validateParkingLotAccess } = require('../utils/roleAuth');

/**
 * 停车场运营商提交变更申请
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
async function submitChangeRequest(req, res) {
  try {
    const { parking_lot_id, request_type, request_data, reason } = req.body;
    const applicantUserId = req.user.id;

    // 验证必填字段
    if (!parking_lot_id || !request_type || !request_data) {
      return res.status(400).json({
        success: false,
        message: '缺少必填字段'
      });
    }

    // 验证申请类型
    const validTypes = ['close_dates', 'activate', 'modify_spaces', 'modify_images', 'modify_info', 'modify_comprehensive'];
    if (!validTypes.includes(request_type)) {
      return res.status(400).json({
        success: false,
        message: '无效的申请类型'
      });
    }

    // 验证用户是否有权限管理该停车场
    const hasAccess = await validateParkingLotAccess(applicantUserId, parking_lot_id);
    if (!hasAccess) {
      return res.status(403).json({
        success: false,
        message: '无权限操作此停车场'
      });
    }

    // 获取当前停车场数据作为快照
    const currentDataQuery = `
      SELECT name, total_spaces, image_urls, contact_phone, backup_phone, description, address,
             airport_distance_km, station_distance_km, shuttle_time_minutes, 
             category_id, service_facilities, business_documents, price_rules
      FROM parking_lots 
      WHERE id = ?
    `;
    const currentDataResult = await query(currentDataQuery, [parking_lot_id]);
    const currentData = currentDataResult[0] || {};

    // 检查是否有相同类型的待处理申请
    const existingRequestQuery = `
      SELECT id FROM parking_lot_change_requests 
      WHERE parking_lot_id = ? AND request_type = ? AND status = 'pending'
    `;
    const existingRequest = await query(existingRequestQuery, [parking_lot_id, request_type]);

    if (existingRequest.length > 0) {
      return res.status(400).json({
        success: false,
        message: '该类型申请已存在待处理的申请，请等待审批完成'
      });
    }

    // 插入申请记录
    const insertQuery = `
      INSERT INTO parking_lot_change_requests 
      (parking_lot_id, applicant_user_id, request_type, request_data, current_data, reason)
      VALUES (?, ?, ?, ?, ?, ?)
    `;

    const result = await query(insertQuery, [
      parking_lot_id,
      applicantUserId,
      request_type,
      JSON.stringify(request_data),
      JSON.stringify(currentData),
      reason || ''
    ]);

    res.status(201).json({
      success: true,
      message: '申请提交成功，等待管理员审批',
      data: {
        request_id: result.insertId,
        status: 'pending'
      }
    });

  } catch (error) {
    console.error('提交变更申请错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
}

/**
 * 获取停车场的申请记录列表（运营商端）
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
async function getOperatorChangeRequests(req, res) {
  try {
    const { parking_lot_id } = req.params;
    const { page = 1, limit = 20, status } = req.query;
    const userId = req.user.id;

    // 验证用户权限
    const hasAccess = await validateParkingLotAccess(userId, parking_lot_id);
    if (!hasAccess) {
      return res.status(403).json({
        success: false,
        message: '无权限访问此停车场的申请记录'
      });
    }

    const pageNum = parseInt(page) || 1;
    const limitNum = parseInt(limit) || 20;
    const offset = (pageNum - 1) * limitNum;

    let whereClause = 'WHERE cr.parking_lot_id = ?';
    let queryParams = [parking_lot_id];

    if (status && ['pending', 'approved', 'rejected'].includes(status)) {
      whereClause += ' AND cr.status = ?';
      queryParams.push(status);
    }

    // 查询总数
    const countQuery = `
      SELECT COUNT(*) as total
      FROM parking_lot_change_requests cr
      ${whereClause}
    `;
    const countResult = await query(countQuery, queryParams);
    const total = countResult[0].total;

    // 查询申请列表
    const requestsQuery = `
      SELECT 
        cr.id,
        cr.request_type,
        cr.reason,
        cr.status,
        cr.admin_comment,
        cr.processed_at,
        cr.created_at,
        pl.name as parking_lot_name
      FROM parking_lot_change_requests cr
      LEFT JOIN parking_lots pl ON cr.parking_lot_id = pl.id
      ${whereClause}
      ORDER BY cr.created_at DESC
      LIMIT ${limitNum} OFFSET ${offset}
    `;

    const requests = await query(requestsQuery, queryParams);

    res.status(200).json({
      success: true,
      data: {
        list: requests,
        total,
        page: pageNum,
        limit: limitNum,
        totalPages: Math.ceil(total / limitNum)
      }
    });

  } catch (error) {
    console.error('获取申请记录错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
}

/**
 * 获取所有变更申请列表（管理员端）
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
async function getAllChangeRequests(req, res) {
  try {
    const { page = 1, limit = 20, status, request_type, parking_lot_name } = req.query;

    const pageNum = parseInt(page) || 1;
    const limitNum = parseInt(limit) || 20;
    const offset = (pageNum - 1) * limitNum;

    let whereClause = 'WHERE 1=1';
    let queryParams = [];

    // 状态筛选
    if (status && ['pending', 'approved', 'rejected'].includes(status)) {
      whereClause += ' AND cr.status = ?';
      queryParams.push(status);
    }

    // 申请类型筛选
    if (request_type && ['close_dates', 'activate', 'modify_spaces', 'modify_images', 'modify_info', 'modify_comprehensive'].includes(request_type)) {
      whereClause += ' AND cr.request_type = ?';
      queryParams.push(request_type);
    }

    // 停车场名称筛选
    if (parking_lot_name && parking_lot_name.trim()) {
      whereClause += ' AND pl.name LIKE ?';
      queryParams.push(`%${parking_lot_name.trim()}%`);
    }

    // 查询总数
    const countQuery = `
      SELECT COUNT(*) as total
      FROM parking_lot_change_requests cr
      LEFT JOIN parking_lots pl ON cr.parking_lot_id = pl.id
      ${whereClause}
    `;
    const countResult = await query(countQuery, queryParams);
    const total = countResult[0].total;

    // 查询申请列表
    const requestsQuery = `
      SELECT 
        cr.id,
        cr.parking_lot_id,
        cr.request_type,
        cr.request_data,
        cr.current_data,
        cr.reason,
        cr.status,
        cr.admin_comment,
        cr.processed_at,
        cr.created_at,
        pl.name as parking_lot_name,
        u.nickname as applicant_name,
        u.phone_number as applicant_phone
      FROM parking_lot_change_requests cr
      LEFT JOIN parking_lots pl ON cr.parking_lot_id = pl.id
      LEFT JOIN users u ON cr.applicant_user_id = u.id
      ${whereClause}
      ORDER BY cr.created_at DESC
      LIMIT ${limitNum} OFFSET ${offset}
    `;

    const requests = await query(requestsQuery, queryParams);

    // 格式化数据
    const formattedRequests = requests.map(request => ({
      ...request,
      request_data: typeof request.request_data === 'string'
        ? JSON.parse(request.request_data)
        : request.request_data,
      current_data: typeof request.current_data === 'string'
        ? JSON.parse(request.current_data)
        : request.current_data
    }));

    res.status(200).json({
      success: true,
      data: {
        list: formattedRequests,
        total,
        page: pageNum,
        limit: limitNum,
        totalPages: Math.ceil(total / limitNum)
      }
    });

  } catch (error) {
    console.error('获取所有申请记录错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
}

/**
 * 管理员审批申请
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
async function processChangeRequest(req, res) {
  console.log('🚀🚀🚀 进入 processChangeRequest 函数 🚀🚀🚀');
  console.log('请求参数:', req.params);
  console.log('请求体:', req.body);
  console.log('管理员信息:', req.admin);
  
  try {
    const { requestId } = req.params;
    const { action, admin_comment } = req.body;
    const adminUserId = req.admin.id;
    
    console.log('=== 开始处理变更申请 ===');
    console.log('申请ID:', requestId);
    console.log('操作:', action);
    console.log('管理员ID:', adminUserId);

    // 验证参数
    if (!['approve', 'reject'].includes(action)) {
      return res.status(400).json({
        success: false,
        message: '无效的操作类型'
      });
    }

    // 获取申请详情
    const requestQuery = `
      SELECT * FROM parking_lot_change_requests 
      WHERE id = ? AND status = 'pending'
    `;
    const requestResult = await query(requestQuery, [requestId]);

    if (requestResult.length === 0) {
      return res.status(404).json({
        success: false,
        message: '申请不存在或已处理'
      });
    }

    const changeRequest = requestResult[0];
    const newStatus = action === 'approve' ? 'approved' : 'rejected';

    // 开始事务
    const connection = await beginTransaction();

    try {
      // 更新申请状态
      const updateRequestQuery = `
        UPDATE parking_lot_change_requests 
        SET status = ?, admin_user_id = ?, admin_comment = ?, processed_at = NOW()
        WHERE id = ?
      `;
      await connection.execute(updateRequestQuery, [newStatus, adminUserId, admin_comment || '', requestId]);

      // 如果是批准，则应用变更
      if (action === 'approve') {
        await applyChangeRequestWithConnection(changeRequest, connection);
      }

      await commitTransaction(connection);

      res.status(200).json({
        success: true,
        message: action === 'approve' ? '申请已批准并生效' : '申请已拒绝',
        data: {
          request_id: requestId,
          status: newStatus
        }
      });

    } catch (error) {
      await rollbackTransaction(connection);
      throw error;
    }

  } catch (error) {
    console.error('处理申请错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
}

/**
 * 应用变更申请到停车场
 * @param {Object} changeRequest - 变更申请对象
 */
async function applyChangeRequest(changeRequest) {
  const { parking_lot_id, request_type, request_data } = changeRequest;
  const requestData = typeof request_data === 'string' ? JSON.parse(request_data) : request_data;

  switch (request_type) {
    case 'close_dates':
      // 处理停用申请
      await applyCloseDatesRequest(parking_lot_id, requestData);
      break;
    case 'activate':
      // 处理启用申请
      await applyActivateRequest(parking_lot_id, requestData);
      break;

    case 'modify_spaces':
      // 处理车位数修改申请
      await applyModifySpacesRequest(parking_lot_id, requestData);
      break;

    case 'modify_images':
      // 处理图片修改申请
      await applyModifyImagesRequest(parking_lot_id, requestData);
      break;

    case 'modify_info':
      // 处理基本信息修改申请
      await applyModifyInfoRequest(parking_lot_id, requestData);
      break;

    case 'modify_comprehensive':
      // 处理统一变更申请
      await applyComprehensiveChangeRequest(parking_lot_id, requestData);
      break;

    default:
      throw new Error(`未知的申请类型: ${request_type}`);
  }
}

/**
 * 使用连接对象应用变更申请到停车场
 * @param {Object} changeRequest - 变更申请对象
 * @param {Object} connection - 数据库连接对象
 */
async function applyChangeRequestWithConnection(changeRequest, connection) {
  console.log('=== 开始应用变更申请 ===');
  console.log('申请类型:', changeRequest.request_type);
  console.log('停车场ID:', changeRequest.parking_lot_id);
  
  const { parking_lot_id, request_type, request_data } = changeRequest;
  const requestData = typeof request_data === 'string' ? JSON.parse(request_data) : request_data;

  switch (request_type) {
    case 'close_dates':
      // 处理停用申请
      await applyCloseDatesRequestWithConnection(parking_lot_id, requestData, connection);
      break;
    case 'activate':
      // 处理启用申请
      await applyActivateRequestWithConnection(parking_lot_id, requestData, connection);
      break;

    case 'modify_spaces':
      // 处理车位数修改申请
      await applyModifySpacesRequestWithConnection(parking_lot_id, requestData, connection);
      break;

    case 'modify_images':
      // 处理图片修改申请
      await applyModifyImagesRequestWithConnection(parking_lot_id, requestData, connection);
      break;

    case 'modify_info':
      // 处理基本信息修改申请
      await applyModifyInfoRequestWithConnection(parking_lot_id, requestData, connection);
      break;

    case 'modify_comprehensive':
      // 处理统一变更申请
      await applyComprehensiveChangeRequestWithConnection(parking_lot_id, requestData, connection);
      break;

    default:
      throw new Error(`未知的申请类型: ${request_type}`);
  }
}

/**
 * 应用停用申请
 */
async function applyCloseDatesRequest(parkingLotId, requestData) {
  // 直接将停车场状态改为停用
  const updateQuery = `
    UPDATE parking_lots 
    SET status = 'inactive', updated_at = NOW() 
    WHERE id = ?
  `;
  await query(updateQuery, [parkingLotId]);
}

/**
 * 应用启用申请
 */
async function applyActivateRequest(parkingLotId, requestData) {
  // 直接将停车场状态改为启用
  const updateQuery = `
    UPDATE parking_lots 
    SET status = 'approved', updated_at = NOW() 
    WHERE id = ?
  `;
  await query(updateQuery, [parkingLotId]);
}

/**
 * 使用连接对象应用停用申请
 */
async function applyCloseDatesRequestWithConnection(parkingLotId, requestData, connection) {
  // 直接将停车场状态改为停用
  const updateQuery = `
    UPDATE parking_lots 
    SET status = 'inactive', updated_at = NOW() 
    WHERE id = ?
  `;
  await connection.execute(updateQuery, [parkingLotId]);
}

/**
 * 使用连接对象应用启用申请
 */
async function applyActivateRequestWithConnection(parkingLotId, requestData, connection) {
  // 直接将停车场状态改为启用
  const updateQuery = `
    UPDATE parking_lots 
    SET status = 'approved', updated_at = NOW() 
    WHERE id = ?
  `;
  await connection.execute(updateQuery, [parkingLotId]);
}

/**
 * 应用车位数修改申请
 */
async function applyModifySpacesRequest(parkingLotId, requestData) {
  const { total_spaces } = requestData;

  if (total_spaces && typeof total_spaces === 'number' && total_spaces >= 0) {
    const updateQuery = `
      UPDATE parking_lots 
      SET total_spaces = ?, updated_at = NOW() 
      WHERE id = ?
    `;
    await query(updateQuery, [total_spaces, parkingLotId]);
  }
}

/**
 * 使用连接对象应用车位数修改申请
 */
async function applyModifySpacesRequestWithConnection(parkingLotId, requestData, connection) {
  const { total_spaces } = requestData;

  if (total_spaces && typeof total_spaces === 'number' && total_spaces >= 0) {
    const updateQuery = `
      UPDATE parking_lots 
      SET total_spaces = ?, updated_at = NOW() 
      WHERE id = ?
    `;
    await connection.execute(updateQuery, [total_spaces, parkingLotId]);
  }
}

/**
 * 应用图片修改申请
 */
async function applyModifyImagesRequest(parkingLotId, requestData) {
  const { image_urls } = requestData;

  if (image_urls && Array.isArray(image_urls)) {
    const updateQuery = `
      UPDATE parking_lots 
      SET image_urls = ?, updated_at = NOW() 
      WHERE id = ?
    `;
    await query(updateQuery, [JSON.stringify(image_urls), parkingLotId]);
  }
}

/**
 * 使用连接对象应用图片修改申请
 */
async function applyModifyImagesRequestWithConnection(parkingLotId, requestData, connection) {
  const { image_urls } = requestData;

  if (image_urls && Array.isArray(image_urls)) {
    const updateQuery = `
      UPDATE parking_lots 
      SET image_urls = ?, updated_at = NOW() 
      WHERE id = ?
    `;
    await connection.execute(updateQuery, [JSON.stringify(image_urls), parkingLotId]);
  }
}

/**
 * 应用基本信息修改申请
 */
async function applyModifyInfoRequest(parkingLotId, requestData) {
  const allowedFields = ['name', 'contact_phone', 'description'];
  const updateFields = [];
  const updateValues = [];

  for (const field of allowedFields) {
    if (requestData[field] !== undefined) {
      updateFields.push(`${field} = ?`);
      updateValues.push(requestData[field]);
    }
  }

  if (updateFields.length > 0) {
    updateFields.push('updated_at = NOW()');
    updateValues.push(parkingLotId);

    const updateQuery = `
      UPDATE parking_lots 
      SET ${updateFields.join(', ')} 
      WHERE id = ?
    `;
    await query(updateQuery, updateValues);
  }
}

/**
 * 使用连接对象应用基本信息修改申请
 */
async function applyModifyInfoRequestWithConnection(parkingLotId, requestData, connection) {
  const allowedFields = ['name', 'contact_phone', 'description'];
  const updateFields = [];
  const updateValues = [];

  for (const field of allowedFields) {
    if (requestData[field] !== undefined) {
      updateFields.push(`${field} = ?`);
      updateValues.push(requestData[field]);
    }
  }

  if (updateFields.length > 0) {
    updateFields.push('updated_at = NOW()');
    updateValues.push(parkingLotId);

    const updateQuery = `
      UPDATE parking_lots 
      SET ${updateFields.join(', ')} 
      WHERE id = ?
    `;
    await connection.execute(updateQuery, updateValues);
  }
}

/**
 * 应用统一变更申请
 */
async function applyComprehensiveChangeRequest(parkingLotId, requestData) {
  const { name, contact_phone, address, description, total_spaces, new_images, current_images } = requestData;
  const updateFields = [];
  const updateValues = [];

  // 处理基本信息字段
  if (name !== undefined) {
    updateFields.push('name = ?');
    updateValues.push(name);
  }
  if (contact_phone !== undefined) {
    updateFields.push('contact_phone = ?');
    updateValues.push(contact_phone);
  }
  if (address !== undefined) {
    updateFields.push('address = ?');
    updateValues.push(address);
  }
  if (description !== undefined) {
    updateFields.push('description = ?');
    updateValues.push(description);
  }

  // 处理车位数
  if (total_spaces !== undefined && typeof total_spaces === 'number' && total_spaces >= 0) {
    updateFields.push('total_spaces = ?');
    updateValues.push(total_spaces);
  }

  // 处理图片：合并当前保留的图片和新上传的图片
  if (current_images !== undefined || new_images !== undefined) {
    const finalImages = [];
    
    // 添加保留的当前图片
    if (current_images && Array.isArray(current_images)) {
      finalImages.push(...current_images);
    }
    
    // 添加新图片
    if (new_images && Array.isArray(new_images)) {
      finalImages.push(...new_images);
    }
    
    updateFields.push('image_urls = ?');
    updateValues.push(JSON.stringify(finalImages));
  }

  if (updateFields.length > 0) {
    updateFields.push('updated_at = NOW()');
    updateValues.push(parkingLotId);

    const updateQuery = `
      UPDATE parking_lots 
      SET ${updateFields.join(', ')} 
      WHERE id = ?
    `;
    await query(updateQuery, updateValues);
  }
}

/**
 * 使用连接对象应用统一变更申请
 */
async function applyComprehensiveChangeRequestWithConnection(parkingLotId, requestData, connection) {
  console.log('=== 开始应用统一变更申请 ===');
  console.log('停车场ID:', parkingLotId);
  console.log('申请数据:', JSON.stringify(requestData, null, 2));
  
  // 检查关键字段是否存在
  console.log('关键字段检查:');
  console.log('- airport_distance_km:', requestData.airport_distance_km, typeof requestData.airport_distance_km);
  console.log('- station_distance_km:', requestData.station_distance_km, typeof requestData.station_distance_km);
  console.log('- shuttle_time_minutes:', requestData.shuttle_time_minutes, typeof requestData.shuttle_time_minutes);
  console.log('- service_facilities:', requestData.service_facilities, typeof requestData.service_facilities);
  
  const { 
    name, contact_phone, backup_phone, address, description, total_spaces, 
    airport_distance_km, station_distance_km, shuttle_time_minutes, 
    category_id, service_facilities, business_documents, price_rules,
    // 价格规则字段
    price_first_hour, price_per_hour, price_daily_max, free_minutes,
    // 营业执照字段
    business_license_number, legal_representative, registered_address,
    new_images, current_images, new_license_images
  } = requestData;
  const updateFields = [];
  const updateValues = [];

  // 处理基本信息字段
  if (name !== undefined) {
    updateFields.push('name = ?');
    updateValues.push(name);
  }
  if (contact_phone !== undefined) {
    updateFields.push('contact_phone = ?');
    updateValues.push(contact_phone);
  }
  if (backup_phone !== undefined) {
    updateFields.push('backup_phone = ?');
    updateValues.push(backup_phone);
  }
  if (address !== undefined) {
    updateFields.push('address = ?');
    updateValues.push(address);
  }
  if (description !== undefined) {
    updateFields.push('description = ?');
    updateValues.push(description);
  }
  
  // 处理距离信息字段
  if (airport_distance_km !== undefined) {
    const distance = parseFloat(airport_distance_km);
    if (!isNaN(distance) && distance >= 0) {
      updateFields.push('airport_distance_km = ?');
      updateValues.push(distance);
      console.log('更新机场距离:', distance);
    }
  }
  if (station_distance_km !== undefined) {
    const distance = parseFloat(station_distance_km);
    if (!isNaN(distance) && distance >= 0) {
      updateFields.push('station_distance_km = ?');
      updateValues.push(distance);
      console.log('更新高铁站距离:', distance);
    }
  }
  if (shuttle_time_minutes !== undefined) {
    const minutes = parseInt(shuttle_time_minutes);
    if (!isNaN(minutes) && minutes >= 0) {
      updateFields.push('shuttle_time_minutes = ?');
      updateValues.push(minutes);
      console.log('更新摆渡时间:', minutes);
    }
  }
  
  // 处理分类
  if (category_id !== undefined) {
    updateFields.push('category_id = ?');
    updateValues.push(category_id);
  }
  
  // 处理服务设施
  if (service_facilities !== undefined) {
    updateFields.push('service_facilities = ?');
    updateValues.push(JSON.stringify(service_facilities));
    console.log('更新服务设施:', JSON.stringify(service_facilities));
  }
  
  // 处理营业资料
  if (business_documents !== undefined) {
    updateFields.push('business_documents = ?');
    updateValues.push(JSON.stringify(business_documents));
  }
  
  // 处理价格规则
  if (price_rules !== undefined) {
    updateFields.push('price_rules = ?');
    updateValues.push(JSON.stringify(price_rules));
  }

  // 处理车位数
  if (total_spaces !== undefined) {
    const spaces = parseInt(total_spaces);
    if (!isNaN(spaces) && spaces >= 0) {
      updateFields.push('total_spaces = ?');
      updateValues.push(spaces);
      console.log('更新车位数:', spaces);
    }
  }
  
  // 处理价格规则字段
  if (price_first_hour !== undefined) {
    const price = parseFloat(price_first_hour);
    if (!isNaN(price) && price >= 0) {
      updateFields.push('price_first_hour = ?');
      updateValues.push(price);
      console.log('更新首小时价格:', price);
    }
  }
  if (price_per_hour !== undefined) {
    const price = parseFloat(price_per_hour);
    if (!isNaN(price) && price >= 0) {
      updateFields.push('price_per_hour = ?');
      updateValues.push(price);
      console.log('更新后续每小时价格:', price);
    }
  }
  if (price_daily_max !== undefined) {
    const price = parseFloat(price_daily_max);
    if (!isNaN(price) && price >= 0) {
      updateFields.push('price_daily_max = ?');
      updateValues.push(price);
      console.log('更新24小时封顶价格:', price);
    }
  }
  if (free_minutes !== undefined) {
    const minutes = parseInt(free_minutes);
    if (!isNaN(minutes) && minutes >= 0) {
      updateFields.push('free_minutes = ?');
      updateValues.push(minutes);
      console.log('更新免费停车时间:', minutes);
    }
  }
  
  // 处理营业执照信息字段
  if (business_license_number !== undefined) {
    updateFields.push('business_license_number = ?');
    updateValues.push(business_license_number);
    console.log('更新营业执照号:', business_license_number);
  }
  if (legal_representative !== undefined) {
    updateFields.push('legal_representative = ?');
    updateValues.push(legal_representative);
    console.log('更新法人代表:', legal_representative);
  }
  if (registered_address !== undefined) {
    updateFields.push('registered_address = ?');
    updateValues.push(registered_address);
    console.log('更新注册地址:', registered_address);
  }

  // 处理图片：合并当前保留的图片和新上传的图片
  if (current_images !== undefined || new_images !== undefined) {
    const finalImages = [];
    
    // 添加保留的当前图片
    if (current_images && Array.isArray(current_images)) {
      finalImages.push(...current_images);
    }
    
    // 添加新图片
    if (new_images && Array.isArray(new_images)) {
      finalImages.push(...new_images);
    }
    
    updateFields.push('image_urls = ?');
    updateValues.push(JSON.stringify(finalImages));
  }
  
  // 处理营业执照图片：合并当前保留的图片和新上传的图片
  if (requestData.current_license_images !== undefined || new_license_images !== undefined) {
    const finalLicenseImages = [];
    
    // 添加保留的当前营业执照图片
    if (requestData.current_license_images && Array.isArray(requestData.current_license_images)) {
      finalLicenseImages.push(...requestData.current_license_images);
    }
    
    // 添加新营业执照图片
    if (new_license_images && Array.isArray(new_license_images)) {
      finalLicenseImages.push(...new_license_images);
    }
    
    updateFields.push('business_documents = ?');
    updateValues.push(JSON.stringify(finalLicenseImages));
    console.log('更新营业执照图片:', finalLicenseImages.length, '张');
  }

  if (updateFields.length > 0) {
    updateFields.push('updated_at = NOW()');
    updateValues.push(parkingLotId);

    const updateQuery = `
      UPDATE parking_lots 
      SET ${updateFields.join(', ')} 
      WHERE id = ?
    `;
    
    console.log('=== 执行SQL更新 ===');
    console.log('SQL语句:', updateQuery);
    console.log('参数:', updateValues);
    
    const result = await connection.execute(updateQuery, updateValues);
    console.log('SQL执行结果:', {
      affectedRows: result[0]?.affectedRows || result.affectedRows,
      changedRows: result[0]?.changedRows || result.changedRows
    });
    
    // 验证更新后的数据
    const verifyQuery = `
      SELECT name, contact_phone, backup_phone, address, description, total_spaces,
             airport_distance_km, station_distance_km, shuttle_time_minutes, 
             category_id, service_facilities
      FROM parking_lots WHERE id = ?
    `;
    const verifyResult = await connection.execute(verifyQuery, [parkingLotId]);
    console.log('=== 更新后验证查询结果 ===');
    console.log(JSON.stringify(verifyResult[0], null, 2));
    console.log('=== SQL更新完成 ===');
  } else {
    console.log('没有需要更新的字段');
  }
}

module.exports = {
  submitChangeRequest,
  getOperatorChangeRequests,
  getAllChangeRequests,
  processChangeRequest
};